package com.vframework.config.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.vframework.base.exception.BaseException;
import com.vframework.common.constant.SessionConstant;
import com.vframework.system.role.model.RoleBean;
import com.vframework.system.security.service.SecurityService;
import com.vframework.system.user.model.UserBean;

/**
 * 获取用户的角色和权限信息 Created by bamboo on 2017/5/10.
 */
public class ShiroRealm extends AuthorizingRealm {

    public ShiroRealm() {
        super(new AllowAllCredentialsMatcher());
        setAuthenticationTokenClass(UsernamePasswordToken.class);
        // FIXME: 暂时禁用Cache
        setCachingEnabled(false);
    }

    @Autowired
    private SecurityService securityService;

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        System.out.println("身份认证方法： ShiroRealm.doGetAuthenticationInfo()");
        UsernamePasswordToken token = (UsernamePasswordToken) authToken;
        System.out.println("验证当前subject时获取到的token为：" + token.toString());
        UserBean loginUser;
        try {
            loginUser = securityService.queryLoginUserByAccount(token.getUsername());
            // 账号不存在
            if (loginUser == null) {
                throw new UnknownAccountException("账号或密码不正确");
            }
            Object credentials = token.getCredentials();
            if (credentials == null) {
                throw new UnknownAccountException("账号或密码不正确");
            }
            String password = new String((char[]) credentials);
            if (!password.equals(loginUser.getPassword())) {
                throw new IncorrectCredentialsException("账号或密码不正确");
            }
            if ("0".equals(loginUser.getStatus())) {
                throw new LockedAccountException("账号已经禁止登陆");
            }
            List<RoleBean> roleList = null;
            try {
                roleList = securityService.queryRoleByUserId(loginUser.getUserId());
            } catch (BaseException e) {
                e.printStackTrace();
                return null;
            }
            String roleNames = "";
            Set<String> roleSet = new HashSet<String>();
            if (roleList != null && roleList.size() > 0) {
                for (RoleBean role : roleList) {
                    roleNames += role.getRoleName().concat(",");
                    roleSet.add(role.getRoleId());
                }
                roleNames = roleNames.substring(0, roleNames.length() - 1);
            }
            loginUser.setRoleSet(roleList);
            loginUser.setRoleNames(roleNames);
            // 更新log
            Session session = SecurityUtils.getSubject().getSession();
            // session.setAttribute(SessionConstant.SESSION_VALIDATE_CODE, rand);
            session.setAttribute(SessionConstant.SESSION_USER_ID, loginUser.getUserId());
            session.setAttribute(SessionConstant.SESSION_USER_NAME, loginUser.getUserName());
            session.setAttribute(SessionConstant.SESSION_ACCOUNT, loginUser.getAccount());
            session.setAttribute(SessionConstant.SESSION_USER_MOBILE, loginUser.getMobile());
            session.setAttribute(SessionConstant.SESSION_USER_EMAIL, loginUser.getEmail());
            session.setAttribute(SessionConstant.SESSION_P_ORG_ID, loginUser.getPorgId());
//                session.setAttribute(SessionConstant.SESSION_USER_TYPE, loginUser.getUserType());
            session.setAttribute(SessionConstant.SESSION_ORG_ID, loginUser.getOrgId());
            session.setAttribute(SessionConstant.SESSION_ORG_NAME, loginUser.getOrgName());
            session.setAttribute(SessionConstant.SESSION_ORG_TYPE, loginUser.getOrgType());
            session.setAttribute(SessionConstant.SESSION_ORG_LEVEL, loginUser.getOrgLevel());
            session.setAttribute(SessionConstant.SESSION_USER_CITY_CODE, loginUser.getCityCode());
            // session.setAttribute(SessionConstant.SESSION_LOGIN_IP, ip);
            session.setAttribute(SessionConstant.SESSION_USER_ROLE, loginUser.getRoleSet());
            session.setAttribute(SessionConstant.SESSION_USER_ROLE_NAME, loginUser.getRoleNames());
            session.setAttribute(SessionConstant.SESSION_USER, loginUser);
        } catch (BaseException e) {
            e.printStackTrace();
            return null;
        }
        // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
        return new SimpleAuthenticationInfo(loginUser.getAccount(), loginUser.getPassword(), getName());
    }

    /**
     * 权限认证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("##################执行Shiro权限认证##################");
        // String loginName =
        // (String)super.getAvailablePrincipal(principalCollection);
        UserBean user = (UserBean) principalCollection.getPrimaryPrincipal();
        if (user != null) {
            List<RoleBean> roleList = null;
            try {
                roleList = securityService.queryRoleByUserId(user.getUserId());
            } catch (BaseException e) {
                e.printStackTrace();
                return null;
            }
            String roleNames = "";
            Set<String> roleSet = new HashSet<String>();
            if (roleList != null && roleList.size() > 0) {
                for (RoleBean role : roleList) {
                    roleNames += role.getRoleName().concat(",");
                    roleSet.add(role.getRoleId());
                }
                roleNames = roleNames.substring(0, roleNames.length() - 1);
            }
            user.setRoleSet(roleList);
            user.setRoleNames(roleNames);
            Session session = SecurityUtils.getSubject().getSession();
            // session.setAttribute(SessionConstant.SESSION_VALIDATE_CODE,
            // rand);
            session.setAttribute(SessionConstant.SESSION_USER_ID, user.getUserId());
            session.setAttribute(SessionConstant.SESSION_USER_NAME, user.getUserName());
            session.setAttribute(SessionConstant.SESSION_ACCOUNT, user.getAccount());
            session.setAttribute(SessionConstant.SESSION_USER_MOBILE, user.getMobile());
            session.setAttribute(SessionConstant.SESSION_USER_EMAIL, user.getEmail());
//            session.setAttribute(SessionConstant.SESSION_USER_TYPE, user.getUserType());
            session.setAttribute(SessionConstant.SESSION_ORG_ID, user.getOrgId());
            session.setAttribute(SessionConstant.SESSION_P_ORG_ID, user.getPorgId());
            session.setAttribute(SessionConstant.SESSION_ORG_NAME, user.getOrgName());
            session.setAttribute(SessionConstant.SESSION_ORG_TYPE, user.getOrgType());
            session.setAttribute(SessionConstant.SESSION_ORG_LEVEL, user.getOrgLevel());
            session.setAttribute(SessionConstant.SESSION_USER_CITY_CODE, user.getCityCode());
            // session.setAttribute(SessionConstant.SESSION_LOGIN_IP, ip);
            session.setAttribute(SessionConstant.SESSION_USER_ROLE, user.getRoleSet());
            session.setAttribute(SessionConstant.SESSION_USER_ROLE_NAME, user.getRoleNames());
            session.setAttribute(SessionConstant.SESSION_USER, user);
            // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 用户的角色集合
            info.addRoles(roleSet);
            Set<String> permissionSet = new HashSet<String>();
            permissionSet.add("权限添加");
            // 用户的权限集合
            info.setStringPermissions(permissionSet);
            return info;
        }
        return null;
    }
}